package gocrypto

import (
	"crypto/aes"
	"crypto/rand"
	"encoding/base64"
	"io"
)

// GenerateAESKey 生成AES密钥
func GenerateAESKey() string {
	key := make([]byte, 16)
	_, _ = io.ReadFull(rand.Reader, key)
	return base64.StdEncoding.EncodeToString(key)
}

// AESEncrypt AES加密
func AESEncrypt(key string, value string) (string, error) {
	key0, err := base64.StdEncoding.DecodeString(key)
	if err != nil {
		return "", err
	}
	src := []byte(value)
	cipher, err := aes.NewCipher(generatorAESKey(key0))
	if err != nil {
		return "", err
	}
	if value == "" {
		return "", nil
	}
	length := (len(src) + aes.BlockSize) / aes.BlockSize
	plain := make([]byte, length*aes.BlockSize)
	copy(plain, src)
	pad := byte(len(plain) - len(src))
	for i := len(src); i < len(plain); i++ {
		plain[i] = pad
	}
	dst := make([]byte, len(plain))
	// 分组分块加密
	for bs, be := 0, cipher.BlockSize(); bs <= len(src); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Encrypt(dst[bs:be], plain[bs:be])
	}
	return base64.StdEncoding.EncodeToString(dst), nil
}

// AESDecrypt AES解密
func AESDecrypt(key string, value string) (string, error) {
	key0, err := base64.StdEncoding.DecodeString(key)
	if err != nil {
		return "", err
	}
	src, err := base64.StdEncoding.DecodeString(value)
	if err != nil {
		return "", err
	}
	cipher, err := aes.NewCipher(generatorAESKey(key0))
	if err != nil {
		return "", err
	}
	if value == "" {
		return "", nil
	}
	decrypted := make([]byte, len(src))
	//
	for bs, be := 0, cipher.BlockSize(); bs < len(src); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Decrypt(decrypted[bs:be], src[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}
	return string(decrypted[:trim]), nil
}

// generatorAESKey 生成AES密钥
func generatorAESKey(key []byte) (genKey []byte) {
	if len(key) == 0 {
		var key0 []byte
		return key0
	}
	genKey = make([]byte, 16)
	copy(genKey, key)
	for i := 16; i < len(key); {
		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
			genKey[j] ^= key[i]
		}
	}
	return genKey
}
